package serv

import (
	"fmt"
	"log"
	"net"
	"netfly/comm"
	"strings"
)

func HandlePortConn(c net.Conn, conf *comm.ClientConf) {
	// prepair
	uid := ClientListPush(c)
	// send pair msg
	strMsg := fmt.Sprintf(`{"token":"%v","ask":"pair","uid":"%v"}`, conf.Token, uid)
	comm.SendCtrlMsg(strMsg, conf.CtrlConn)
	log.Println("PortServer Send pair req", strMsg)
}

func RunPortServer(strAddr string, c *comm.ClientConf) {
	log.Println("Listen Port Server", strAddr)
	sListen, err := net.Listen("tcp", strAddr)
	if err != nil {
		log.Println("Listen", strAddr, "Error:", err.Error())
		return
	}
	defer sListen.Close()

	strPort := strings.Split(strAddr, ":")[1]
	v, ok := c.PortServ[strPort]
	if ok {
		(*v).Close()
	}
	c.PortServ[strPort] = &sListen

	for {
		cConn, err := sListen.Accept()
		if err != nil {
			break
		}
		HandlePortConn(cConn, c)
	}

	log.Println("Port Server", strAddr, "Exit!")
}
